package com.self.cloudmall.pms.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.self.cloudmall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @version v1.0
 * @ClassName: 阿里云oss上传
 * @Description:
 */
@RestController
@RequestMapping("/pms/oss/")
@Slf4j
public class OSSController {

    @Value("${alibaba.cloud.bucket}")
    private String bucket;
    @Value("${alibaba.cloud.endpoint}")
    private String endpoint;
    @Value("${alibaba.cloud.access-key}")
    private String accessKey;

    @Autowired
    private OSS ossClient;

    /**
     * @Title: 浏览器发送请求，服务端进行签名，把参数返回给客户，客户直接请求oss
     * @Description:
     * @Param []
     * @Return java.util.Map<java.lang.String,java.lang.Object>
     */
    @GetMapping("sign")
    public R sign(){
        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL，请将下面的IP和Port配置为您自己的真实信息。
        //String callbackUrl = "http://88.88.88.88:8888";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dir = dateFormat.format(new Date())+"/"; // 用户上传文件时指定的前缀。
        log.info("oss上传的dir:{}",dir);
        Map<String, String> respMap = new LinkedHashMap<String, String>();
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap.put("accessId", accessKey);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
        } catch (Exception e) {
            log.error("阿里云OSS签名报错：",e);
        } finally {
            ossClient.shutdown();
        }

        return R.ok().put("data",respMap);
    }
}
